﻿using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
using System;
using System.Collections.Generic;
using System.Text;
using Umi.Crypto.Abstraction.Ciphers;
using Umi.Crypto.Abstraction.Keys;

namespace Umi.Web.Crypto.Crypto.Rsa
{
    public class RsaCryptoService : ICryptoService
    {
        private readonly IBufferedCipher _cipher;

        public RsaCryptoService(string name)
        {
            if (name.IndexOf("rsa", StringComparison.OrdinalIgnoreCase) < 0)
                throw new ArgumentException($"name {name} not allowed");
            _cipher = CipherUtilities.GetCipher(name);
        }

        public string Name => _cipher.AlgorithmName;

        public byte[] Crypto(byte[] data, KeyParameter key)
        {
            if (key is RsaKeyParameter rsaKey)
            {
                _cipher.Init(true, rsaKey.Parameters);
                return _cipher.DoFinal(data);
            }
            throw new NotSupportedException();
        }

        public byte[] Decrypto(byte[] data, KeyParameter key)
        {
            if (key is RsaKeyParameter rsaKey)
            {
                _cipher.Init(false, rsaKey.Parameters);
                return _cipher.DoFinal(data);
            }
            throw new NotSupportedException();
        }
    }
}
